package com.koicarp.university.graduate.auth.translator;

import com.koicarp.university.graudate.common.dao.SysUserDao;
import com.koicarp.university.graudate.common.constant.BaseConstant;
import com.koicarp.university.graudate.common.utils.UniversityResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * @auther liutao
 * @Date 2020-08-17 16:53:36
 */
@Slf4j
@Component
public class UniversityWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity translate(Exception e) {
        ResponseEntity.BodyBuilder status=ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        UniversityResponse response=new UniversityResponse();
        String message="认证失败";
//        log.error(message,e);
        if (e instanceof UnsupportedGrantTypeException){
            message = "不支持该认证类型";
            response.code(BaseConstant.COMMON_FAIL_0000);
            response.message(message);
            return  status.body(response);
        }
        if(e instanceof InvalidGrantException){
            if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token")){
                message = "refresh token 失效";
                return status.body(response.message(message));
            }
            if (StringUtils.containsIgnoreCase(e.getMessage(), "locked")){
                message = "用户已被锁定，请联系管理员";
                response.message(message);
                response.code(BaseConstant.USER_ACCOUNT_DISABLE_2005);
                return status.body(response);
            }
            /*账号或密码错误*/
            message = BaseConstant.USER_PASSWORD_ERROR;
            response.message(message);
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            return status.body(response);
        }
        return status.body(response.message(message));
    }
}
